package com.coffee.common.convert;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.coffee.common.annotation.ExcelDict;
import com.coffee.common.util.DictUtil;

import java.lang.reflect.Field;

/**
 * Excel数据字典转换器
 *
 * @author Kevin
 */
public class ExcelDictConverter implements Converter<String> {

    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Field field = excelContentProperty.getField();
        String dictCode = AnnotationUtil.getAnnotationValue(field, ExcelDict.class);
        String dictValue = DictUtil.getDictValue(dictCode, cellData.getStringValue());
        return StrUtil.isBlank(dictValue) ? cellData.getStringValue() : dictValue;
    }

    @Override
    public WriteCellData convertToExcelData(String s, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Field field = excelContentProperty.getField();
        String dictCode = AnnotationUtil.getAnnotationValue(field, ExcelDict.class);
        String dictLabel = DictUtil.getDictLabel(dictCode, s);
        return new WriteCellData(StrUtil.isBlank(dictLabel) ? s : dictLabel);
    }

}
